/** Copyright 2020 Tianshu AI Platform. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================
 */
import { isNil, isFunction } from 'lodash';
import { line as d3Line } from 'd3';

import { defaultColor } from '@/views/dataset/util';

export default {
  name: 'PolylineRender',
  functional: true,
  props: {
    points: Array,
    curve: Function,
    fill: String,
    offset: Function,
  },
  render(h, context) {
    const { props } = context;
    const { fill, points = [], offset } = props;

    if (isNil(points)) return null;

    const { style } = context.data;
    const line = d3Line()
      .x((d) => d.x)
      .y((d) => d.y);

    if (props.curve) {
      line.curve(props.curve);
    }

    const bgColor = fill || defaultColor;

    const restProps = {
      attrs: context.data.attrs,
      on: context.data.on,
    };

    const nextData = isFunction(offset) ? points.map(offset) : points;

    return (
      <path
        class="interactive"
        d={line(nextData)}
        stroke={bgColor}
        fill={bgColor}
        stroke-width={2}
        {...restProps}
        style={style}
      />
    );
  },
};
